#!/anaconda3/envs/Script/bin python3.8
# -*- coding: utf-8 -*-
# ---
# @Software: PyCharm
# @File: __init__.py.py
# @Author: AllenFu
# @Institution: NCHU, China
# @E-mail: nchufujianjian@126.com
# @Site: 启动初始化类
# @Time: 11月 25, 2020
# ---
from flask import Flask
from flask_socketio import SocketIO
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

import environment as e
from app.vendor.exception_api import ExceptionApi
from app.vendor.res_code import Code
from config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_POOL_SIZE, UPLOAD_FOLDER, SQLALCHEMY_TRACK_MODIFICATIONS, \
    MAX_CONTENT_LENGTH

env_name = e.read()
app = Flask(__name__)

app.config['UPLOAD_FOLDER']=UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH']=MAX_CONTENT_LENGTH
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS

# 实例化websocket
async_mode = 'gevent'
socketio = SocketIO(app, async_mode=async_mode)

#  实例化数据库连接池
engine = create_engine(SQLALCHEMY_DATABASE_URI, pool_size=SQLALCHEMY_POOL_SIZE)
DBSession = sessionmaker(bind=engine)
dBSession = DBSession()

@app.teardown_appcontext
def shutdown_session(exception=None):
    '''
    当flask上下文关闭的之前手动关闭数据库会话
    '''
    dBSession.close()

@app.errorhandler(Exception)
def err_handler(e):
    '''全局异常处理，记录日志'''
    return ExceptionApi(Code.ERROR, e)


if env_name == 'socket':
    from app.controller import socket_controller
    @socketio.on_error_default
    def err_handler(e):
        return ExceptionApi(Code.ERROR, e)

if env_name == 'run' or env_name=='restful':
    from app.controller.admincontroller import admin
    app.register_blueprint(admin, url_prefix='/admin')

#引入数据库事件
from  app.events import db_operate_log

if env_name == 'run' or env_name == 'restful':
    pass
